package main

import (
	"agent-service/configs"
	"agent-service/handler"
	report2 "agent-service/report"
	"context"
	"log"
	"path"
	"runtime"

	"github.com/robfig/cron/v3"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {
	// 加载配置文件
	_, file, _, _ := runtime.Caller(0)
	configPath := path.Dir(path.Dir(file)) + "/configs/config.json"
	configs.LoadConfig(configPath)

	log.Printf("start access %s", configs.GetConfig().JudgeUrl)

	// cron 测试
	timing := cron.New(cron.WithSeconds())
	timing.AddFunc(configs.GetConfig().Spec, func() {
		conn, err := grpc.Dial(configs.GetConfig().JudgeUrl, grpc.WithTransportCredentials(insecure.NewCredentials()))
		if err != nil {
			log.Fatalf("cannot access %s, err: %v", configs.GetConfig().JudgeUrl, err)
		}
		defer conn.Close()

		c := report2.NewReportServiceClient(conn)
		ip_addr := make(map[string]string)
		ip_addr["ip"] = handler.GetIp()

		val := handler.GetCpuPercent() / 100

		cpu_res, err := c.Report(context.Background(), &report2.ReportReq{
			Timestamp:  handler.GetTime().Unix(),
			Metric:     "cpu_rate",
			Dimensions: ip_addr,
			Value:      val,
		})
		if err != nil {
			log.Fatalf("report cpu rate error: %v", err)
		}
		log.Printf("cpu response code:%d", cpu_res.GetCode())
		log.Printf("cpu response msg:%s", cpu_res.GetMsg())
		log.Printf("cpu_rate:%f", val)

		val = handler.GetMemPercent() / 100
		mem_res, err := c.Report(context.Background(), &report2.ReportReq{
			Timestamp:  handler.GetTime().Unix(),
			Metric:     "mem_rate",
			Dimensions: ip_addr,
			Value:      val,
		})
		if err != nil {
			log.Fatalf("report memory rate error: %v", err)
		}
		log.Printf("mem response code:%d", mem_res.GetCode())
		log.Printf("mem response code:%s", mem_res.GetMsg())
		log.Printf("mem_rate:%f", val)
	})

	timing.Start()
	defer timing.Stop()
	select {}
}
